package com.spring.app.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import com.spring.app.dao.BuyerRepository;
import com.spring.app.dao.ItemRepository;
import com.spring.app.dao.TransactionFileRepository;
import com.spring.app.domain.BuyerData;
import com.spring.app.domain.ItemData;
import com.spring.app.domain.TransactionFile;
import com.spring.app.genpostagelabel.Utils;
import com.spring.app.util.CsvFileUtil;
import com.spring.app.util.ExcelFileUtil;

@Service
public class BuyerService {

	@Autowired
	private BuyerRepository buyerRepository;
	@Autowired
	private TransactionFileRepository transactionFileRepository;
	@Autowired
	private ExcelFileUtil excelFileUtil;
	@Autowired
	CsvFileUtil csvFileUtil;

	public void  save(List buyerDetails,TransactionFile tf) {

		TransactionFile tfEntity=transactionFileRepository.save(tf);

		buyerRepository.save(buyerDetails);	

	}

	public String   getAllFromTransactionFile(){
		List<TransactionFile> all=	transactionFileRepository.findAll();
		//String out="<table class='table table-striped' align='center' style='width: 80%'><thead><tr><th>File Name</th><th>Uploaded On</th></tr></thead><tbody>";
		String out = "<form>";
		for(TransactionFile tf:all){
			//out+="<tr><td><a onclick='generatePostageLabel(\""+tf.getFileName()+"\")'>"+tf.getFileName()+"</a></td><td>"+tf.getImportDate()+"</td></tr>";
			
			out+="<input type=\"checkbox\" name=\""+tf.getFileName()+"\" value=\""+tf.getIdFile()+"\">"+tf.getFileName()+"            "+tf.getImportDate()+"<br>";
		}
		//out+="</tbody></table>";
		out+= "<button onclick=\"myFunction()\">Click me</button> </form>";
		return out;

	}

	public void generatePostageLabel(Map model) { 
		excelFileUtil.generatePostageLabels(model);
	}

	public TransactionFile saveTransactionFile(TransactionFile transactionFile) {

		TransactionFile tfEntity=transactionFileRepository.save(transactionFile);

		return tfEntity;
	}

	public String getInventoryFileName(String fileName) {
		String tmp=new String(fileName);
		int i=0;
		while(!Utils.isEmpty(transactionFileRepository.findByFileName(fileName))){
			fileName=tmp.substring(0,tmp.lastIndexOf("."))+"_"+i+fileName.substring(fileName.lastIndexOf("."));
			i++;
		}

		return fileName;	
	}


	@Async
	public Future<Map> readExcel(String fileName) throws Exception{

		Map result=new HashMap();
		if(fileName.endsWith("csv")){
			result=csvFileUtil.readCsv(fileName);
		}else
			result=excelFileUtil.readExcel(fileName);

		return new AsyncResult<Map>(result);	 	
	}


}
